package com.raymond.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化工具类
 *
 * @author :  raymond
 * @version :  1.0
 * @date :  2019/7/17
 */
@Slf4j
public class SerializeUtil {
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream bs = null;
        try {
            // 序列化
            bs = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bs);
            oos.writeObject(object);
            return bs.toByteArray();
        } catch (Exception e) {
            log.error("序列化异常", e);
        }
        return null;
    }

    public static Object unSerialize( byte[] bytes) {
        ByteArrayInputStream bs = null;
        try {
            // 反序列化
            bs = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bs);
            return ois.readObject();
        } catch (Exception e) {
            log.error("反序列化异常", e);
        }
        return null;
    }
}
